package lab.ui;

import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;

public class ImageButton extends JButton {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private ImageIcon icon = null;
	private ImageIcon selectedIcon = null;
	private ImageIcon rolloverIcon = null;
	private ImageIcon backgroundIcon = null;

	public ImageButton(String text, ImageIcon... icons) {
		super(text);
		if (icons.length > 0) {
			icon = icons[0];
			backgroundIcon = icon;
		}
		if (icons.length > 1) {
			rolloverIcon = icons[1];
		}
		if (icons.length > 2) {
			selectedIcon = icons[2];
		}
		setOpaque(true);
		setBorderPainted(false);
		setFocusPainted(false);
		setContentAreaFilled(false);
		setMargin(new Insets(0, 0, 0, 0));
		setPreferredSize(new Dimension(icon.getIconWidth(), icon.getIconHeight()));
		addMouseListener(new MouseListener() {

			public void mouseClicked(MouseEvent e) {
			}

			public void mousePressed(MouseEvent e) {
				backgroundIcon = selectedIcon;
			}

			public void mouseReleased(MouseEvent e) {
				backgroundIcon = rolloverIcon;
			}

			public void mouseEntered(MouseEvent e) {
				backgroundIcon = rolloverIcon;
				ImageButton.this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
			}

			public void mouseExited(MouseEvent e) {
				backgroundIcon = icon;
				ImageButton.this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
			}

		});
	}

	@Override
	protected void paintComponent(Graphics g) {
		if (backgroundIcon != null) {
			backgroundIcon.paintIcon(this, g, 0, 0);
		}
		super.paintComponent(g);
	}

	@Override
	public void setPreferredSize(Dimension size) {
		super.setPreferredSize(size);
		if (icon != null) {
			icon = getResizeIcon(icon, size);
		}
		if (selectedIcon != null) {
			selectedIcon = getResizeIcon(selectedIcon, size);
		}
		if (rolloverIcon != null) {
			rolloverIcon = getResizeIcon(rolloverIcon, size);
		}
		if (backgroundIcon != null) {
			backgroundIcon = getResizeIcon(backgroundIcon, size);
		}
	}

	private ImageIcon getResizeIcon(ImageIcon icon, Dimension size) {
		Image temp = icon.getImage().getScaledInstance(size.width, size.height, Image.SCALE_DEFAULT);
		return new ImageIcon(temp);
	}
}